const { pool } = require('../config/db');
const bcrypt = require('bcryptjs');

class User {
  // Get user by ID
  static async findById(id) {
    try {
      console.log('尝试通过ID获取用户:', id);
      
      // 确保ID是有效的
      if (!id || isNaN(parseInt(id))) {
        console.error('提供的用户ID无效:', id);
        throw new Error('无效的用户ID');
      }
      
      const [rows] = await pool.query(
        'SELECT id, username, email, full_name, phone, address, is_admin, created_at FROM users WHERE id = ?',
        [id]
      );
      
      if (!rows || rows.length === 0) {
        console.log('未找到ID为', id, '的用户');
        return null;
      }
      
      console.log('成功通过ID', id, '找到用户');
      return rows[0];
    } catch (error) {
      console.error('查询用户失败:', error.message);
      throw new Error(`获取用户失败: ${error.message}`);
    }
  }

  // Get user by username
  static async findByUsername(username) {
    try {
      const [rows] = await pool.query('SELECT * FROM users WHERE username = ?', [username]);
      return rows[0];
    } catch (error) {
      throw new Error(error.message);
    }
  }

  // Get user by email
  static async findByEmail(email) {
    try {
      const [rows] = await pool.query('SELECT * FROM users WHERE email = ?', [email]);
      return rows[0];
    } catch (error) {
      throw new Error(error.message);
    }
  }

  // Create a new user
  static async create(userData) {
    const { username, email, password, full_name, phone, address } = userData;

    try {
      // Hash password
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(password, salt);

      const [result] = await pool.query(
        'INSERT INTO users (username, email, password, full_name, phone, address) VALUES (?, ?, ?, ?, ?, ?)',
        [username, email, hashedPassword, full_name, phone || null, address || null]
      );

      const [newUser] = await pool.query(
        'SELECT id, username, email, full_name, phone, address, is_admin, created_at FROM users WHERE id = ?',
        [result.insertId]
      );

      return newUser[0];
    } catch (error) {
      throw new Error(error.message);
    }
  }

  // Update user
  static async update(id, userData) {
    const { full_name, phone, address } = userData;

    try {
      await pool.query(
        'UPDATE users SET full_name = ?, phone = ?, address = ? WHERE id = ?',
        [full_name, phone, address, id]
      );

      return this.findById(id);
    } catch (error) {
      throw new Error(error.message);
    }
  }

  // Admin update user
  static async adminUpdate(id, userData) {
    const { email, full_name, phone, address } = userData;

    try {
      await pool.query(
        'UPDATE users SET email = ?, full_name = ?, phone = ?, address = ? WHERE id = ?',
        [email, full_name, phone || null, address || null, id]
      );

      return this.findById(id);
    } catch (error) {
      throw new Error(error.message);
    }
  }

  // Update admin status
  static async updateAdminStatus(id, isAdmin) {
    try {
      await pool.query('UPDATE users SET is_admin = ? WHERE id = ?', [isAdmin, id]);
      return this.findById(id);
    } catch (error) {
      throw new Error(error.message);
    }
  }

  // Change password
  static async changePassword(id, newPassword) {
    try {
      // Hash password
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(newPassword, salt);

      await pool.query('UPDATE users SET password = ? WHERE id = ?', [hashedPassword, id]);
      return true;
    } catch (error) {
      throw new Error(error.message);
    }
  }
}

module.exports = User; 